package com.zxx.coolweather.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zxx.coolweather.MainActivity;
import com.zxx.coolweather.R;
import com.zxx.coolweather.WeatherActivity;
import com.zxx.coolweather.db.City;
import com.zxx.coolweather.db.County;
import com.zxx.coolweather.db.Province;
import com.zxx.coolweather.util.HttpUtil;
import com.zxx.coolweather.util.Utility;

import org.litepal.LitePalApplication;
import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @author zxx on 2021/8/25
 */
public class ChooseAreaFragment extends Fragment {

    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_city = 1;
    public static final int LEVEL_county = 2;
    private ProgressDialog progressDialog;
    private TextView titleText;
    private Button backBtn;
    private ListView listView;
    private ArrayAdapter<String> adapter;
    private List<String> dataList = new ArrayList<>();
    private List<Province> proList;
    private List<City> cityList;
    private List<County> countyList;
    private Province selectPro;
    private City selectCity;
    private County selectCounty;
    private int currentLevel;   //当前选中的级别

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.choose_area, container, false);
        titleText = view.findViewById(R.id.title_text);
        backBtn = view.findViewById(R.id.back_button);
        listView = view.findViewById(R.id.list_view);

        adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (currentLevel == LEVEL_PROVINCE) {
                    selectPro = proList.get(position);
                    queryCity();

                } else if (currentLevel == LEVEL_city) {
                    selectCity = cityList.get(position);
                    queryCounty();

                } else if (currentLevel == LEVEL_county) {
                    String weatherId = countyList.get(position).weatherId;

                    if (getActivity() instanceof MainActivity) {
                        Intent intent = new Intent(getContext(), WeatherActivity.class);
                        intent.putExtra("weather_id", weatherId);
                        startActivity(intent);

                        getActivity().finish();

                    } else if (getActivity() instanceof WeatherActivity) {
                        WeatherActivity activity = (WeatherActivity) getActivity();
                        activity.drawerLayout.closeDrawers();
                        activity.refreshLayout.setRefreshing(true);
                        activity.requestWeather(weatherId);
                    }
                }
            }
        });

        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentLevel == LEVEL_county) {
                    queryCity();
                } else if (currentLevel == LEVEL_city) {
                    queryProvince();
                }
            }
        });

        queryProvince();
    }

    private void queryProvince() {
        titleText.setText("中国");
        backBtn.setVisibility(View.GONE);
        proList = DataSupport.findAll(Province.class);

        if (proList.size() > 0) {
            dataList.clear();
            for (Province province : proList) {
                dataList.add(province.provinceName);
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_PROVINCE;
        } else {
            String url = "http://guolin.tech/api/china";
            queryFromServer(url, "province");
        }
    }

    private void queryCity() {
        titleText.setText(selectPro.provinceName);
        backBtn.setVisibility(View.VISIBLE);
        cityList = DataSupport.where("provinceid = ?", String.valueOf(selectPro.id))
                .find(City.class);

        if (cityList.size() > 0) {
            dataList.clear();
            for (City city : cityList) {
                dataList.add(city.cityName);
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_city;
        } else {
            int proCode = selectPro.provinceCode;
            String url = "http://guolin.tech/api/china/" + proCode;
            queryFromServer(url, "city");
        }
    }

    private void queryCounty() {
        titleText.setText(selectCity.cityName);
        backBtn.setVisibility(View.VISIBLE);
        countyList = DataSupport.where("cityid=?", String.valueOf(selectCity.id))
                .find(County.class);

        if (countyList.size() > 0) {
            dataList.clear();
            for (County county : countyList) {
                dataList.add(county.countyName);
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_county;
        } else {
            int proCode = selectPro.provinceCode;
            int cityCode = selectCity.cityCode;
            String url = "http://guolin.tech/api/china/" + proCode + "/" + cityCode;
            queryFromServer(url, "county");
        }
    }

    private void queryFromServer(String url, final String type) {
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String repStr = response.body().string();
                boolean result = false;
                if ("province".equals(type)) {
                    result = Utility.handleProvinceResponse(repStr);
                } else if ("city".equals(type)) {
                    result = Utility.handleCityResponse(repStr, selectPro.id);
                } else if ("county".equals(type)) {
                    result = Utility.handleCountyResponse(repStr, selectCity.id);
                }

                if (result) {
                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)) {
                                queryProvince();
                            } else if ("city".equals(type)) {
                                queryCity();
                            } else if ("county".equals(type)) {
                                queryCounty();
                            }
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                if (getActivity() != null)
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
                        }
                    });
            }
        });
    }

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();

    }

    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }
}
